#include "com_timer.h"

volatile uint64_t System_1ms  = 0;

/*如果Period=N*10，那么每隔N毫秒中断一次。*/
void Sys_Timer3Init(void){
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
	NVIC_InitTypeDef NVIC_InitStructure;

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //时钟使能

	TIM_TimeBaseStructure.TIM_Period = 9; //设置在下一个更新事件装入活动的自动重装载寄存器周期的值	 计数到N*10为Nms
	TIM_TimeBaseStructure.TIM_Prescaler =(7200-1); //设置用来作为TIMx时钟频率除数的预分频值  10Khz的计数频率  
	TIM_TimeBaseStructure.TIM_ClockDivision = 0; //设置时钟分割:TDTS = Tck_tim
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;  //TIM向上计数模式
	TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure); //根据TIM_TimeBaseInitStruct中指定的参数初始化TIMx的时间基数单位
 
	TIM_ITConfig(      //使能或者失能指定的TIM中断
		TIM3,          //TIM3
		TIM_IT_Update| //TIM 中断源
		TIM_IT_Trigger,//TIM 触发中断源 
		ENABLE         //使能
		);
	/*配置中断优先级*/
	NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;  //TIM3中断
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //先占优先级0级
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;  //从优先级3级
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道被使能
	NVIC_Init(&NVIC_InitStructure);//根据NVIC_InitStruct中指定的参数初始化外设NVIC寄存器

	TIM_Cmd(TIM3, ENABLE);         //使能TIMx外设					 
}

void TIM3_IRQHandler(void)   //TIM3中断服务程序
{
	if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)//检查指定的TIM中断发生与否 
	{
		TIM_ClearITPendingBit(TIM3,TIM_IT_Update);    //清除TIMx的中断标志位
		
        System_1ms++;                                 // 1ms
        
        // ESP8266 判断是否获取数据成功
        if(Usart2ReadFlag) {
            if(ESPGetTime < 200)
                ESPGetTime++;
            if(ESPGetTime > 20)
            {
                if(ESPGetCount == Usart2ReadFlag)
                {
                    Usart2ReadFlag |= (1 << 15);
                    ESPGetCount = 0;
                    ESPGetTime  = 0;     
                }
                else
                {
                    ESPGetCount = Usart2ReadFlag;
                    ESPGetTime  = 0;                   
                }
            }
        }
        else { ESPGetTime = 0; ESPGetCount = 0; }
        
        // 
        if( (SysParameter.U3GetTime<65000) && (Usart3ReadFlag))
            SysParameter.U3GetTime++;
        
        // 空气PM获取间隔时间
        if(AirQuality.GetTime<65000)
            AirQuality.GetTime++;
        
        if(SysParameter.ShowBatteryTime<65000)
            SysParameter.ShowBatteryTime++;
        
        // 侧边跳动时间
        if(SysParameter.SideBeatTime<65000)
            SysParameter.SideBeatTime++;        
    }	
}

















